package com.chuanyun.wechatcheckin.service;

import com.chuanyun.wechatcheckin.model.h3yun.H3yunResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Map;

/**
 * 用户同步服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserSyncService {
    
    private final WechatApiService wechatApiService;
    private final H3yunApiService h3yunApiService;
    
    /**
     * 增量同步用户ID到氚云
     */
    public SyncResult syncUsersToH3yun() {
        String startTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        log.info("开始增量同步用户ID到氚云，开始时间: {}", startTime);
        
        SyncResult result = new SyncResult();
        result.setStartTime(startTime);
        
        try {
            // 1. 从企业微信获取用户ID列表
            log.info("步骤1: 从企业微信获取用户ID列表");
            List<String> wechatUserIds = wechatApiService.getAllUserIds();
            result.setWechatUserCount(wechatUserIds.size());
            log.info("从企业微信获取到 {} 个用户ID", wechatUserIds.size());
            
            // 2. 从氚云查询现有用户ID列表（支持分页查询）
            log.info("步骤2: 从氚云查询现有用户ID列表");
            List<String> h3yunUserIds = new ArrayList<>();
            int pageSize = 500;
            int currentPage = 1;
            boolean hasMoreData = true;
            
            while (hasMoreData) {
                log.info("正在查询第 {} 页数据，每页 {} 条记录", currentPage, pageSize);
                
                H3yunResponse<Object> h3yunResponse = h3yunApiService.queryBizDataByPage(
                    "D29092097f0465225d541acabb2a9da271f5291",
                    pageSize,
                    currentPage,
                    List.of("UserId")  // 使用正确的字段名
                );
                
                if (h3yunResponse.isSuccess() && h3yunResponse.getReturnData() != null) {
                    // 记录原始返回数据
                    log.debug("氚云API第{}页返回数据: {}", currentPage, h3yunResponse.getReturnData());
                    
                    // 解析返回的数据，提取UserID列表
                    List<Map<String, Object>> dataList = parseResponseData(h3yunResponse.getReturnData());
                    log.info("第{}页解析后的数据列表大小: {}", currentPage, dataList.size());
                    
                    if (dataList.isEmpty()) {
                        // 如果当前页没有数据，说明已经查询完毕
                        hasMoreData = false;
                        log.info("第{}页没有数据，查询结束", currentPage);
                    } else {
                        // 处理当前页的数据
                        for (Map<String, Object> data : dataList) {
                            log.debug("处理数据项: {}", data);
                            Object userIdObj = data.get("UserId");  // 修正字段名为UserId
                            if (userIdObj != null) {
                                String userId = userIdObj.toString();
                                h3yunUserIds.add(userId);
                                log.debug("提取到用户ID: {}", userId);
                            } else {
                                log.warn("数据项中未找到UserId字段: {}", data);
                            }
                        }
                        
                        // 如果当前页数据少于pageSize，说明这是最后一页
                        if (dataList.size() < pageSize) {
                            hasMoreData = false;
                            log.info("第{}页数据量({})少于页大小({})，查询结束", currentPage, dataList.size(), pageSize);
                        } else {
                            // 继续查询下一页
                            currentPage++;
                        }
                    }
                } else {
                    log.error("氚云第{}页查询失败 - 成功状态: {}, 返回数据: {}, 错误信息: {}", 
                        currentPage,
                        h3yunResponse.isSuccess(), 
                        h3yunResponse.getReturnData(), 
                        h3yunResponse.getErrorMessage());
                    hasMoreData = false; // 查询失败时停止循环
                }
            }
            
            log.info("分页查询完成，总共获取到 {} 个用户ID", h3yunUserIds.size());
            result.setH3yunExistingCount(h3yunUserIds.size());
            log.info("从氚云查询到 {} 个现有用户ID", h3yunUserIds.size());
            
            // 3. 对比数据，计算需要增加和删除的用户ID
            log.info("步骤3: 对比数据，计算增删差异");
            Set<String> wechatUserSet = new HashSet<>(wechatUserIds);
            Set<String> h3yunUserSet = new HashSet<>(h3yunUserIds);
            
            // 需要新增的用户ID（在企业微信中存在，但在氚云中不存在）
            List<String> usersToAdd = new ArrayList<>();
            for (String userId : wechatUserIds) {
                if (!h3yunUserSet.contains(userId)) {
                    usersToAdd.add(userId);
                }
            }
            
            // 需要删除的用户ID（在氚云中存在，但在企业微信中不存在）
            List<String> usersToDelete = new ArrayList<>();
            for (String userId : h3yunUserIds) {
                if (!wechatUserSet.contains(userId)) {
                    usersToDelete.add(userId);
                }
            }
            
            log.info("数据对比完成 - 需要新增: {} 个, 需要删除: {} 个", usersToAdd.size(), usersToDelete.size());
            
            // 4. 执行删除操作
            if (!usersToDelete.isEmpty()) {
                log.info("步骤4: 删除不存在的用户ID");
                h3yunApiService.batchDeleteUserIds(usersToDelete);
                result.setH3yunDeleteCount(usersToDelete.size());
                log.info("成功删除 {} 个用户ID", usersToDelete.size());
            } else {
                log.info("步骤4: 无需删除用户ID");
                result.setH3yunDeleteCount(0);
            }
            
            // 5. 执行新增操作
            if (!usersToAdd.isEmpty()) {
                log.info("步骤5: 新增用户ID");
                h3yunApiService.batchInsertUserIds(usersToAdd);
                result.setH3yunInsertCount(usersToAdd.size());
                log.info("成功新增 {} 个用户ID", usersToAdd.size());
            } else {
                log.info("步骤5: 无需新增用户ID");
                result.setH3yunInsertCount(0);
            }
            
            result.setSuccess(true);
            result.setMessage("增量同步成功");
            
        } catch (Exception e) {
            log.error("增量同步用户ID失败", e);
            result.setSuccess(false);
            result.setMessage("增量同步失败: " + e.getMessage());
            result.setErrorDetail(e.toString());
        }
        
        String endTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        result.setEndTime(endTime);
        
        log.info("增量同步完成，结果: {}", result.isSuccess() ? "成功" : "失败");
        log.info("同步结束时间: {}", endTime);
        
        return result;
    }
    
    /**
     * 解析氚云API返回的数据
     * @param returnData 返回的数据对象
     * @return 解析后的数据列表
     */
    @SuppressWarnings("unchecked")
    private List<Map<String, Object>> parseResponseData(Object returnData) {
        if (returnData == null) {
            return new ArrayList<>();
        }
        
        log.debug("氚云返回数据类型: {}", returnData.getClass().getSimpleName());
        
        if (returnData instanceof List) {
            // 如果返回的是List，直接转换
            List<Map<String, Object>> dataList = (List<Map<String, Object>>) returnData;
            log.debug("直接解析List，数据条数: {}", dataList.size());
            return dataList;
        } else if (returnData instanceof Map) {
            // 如果返回的是Map，可能包含BizObjectArray字段
            Map<String, Object> dataMap = (Map<String, Object>) returnData;
            log.debug("返回Map结构，包含字段: {}", dataMap.keySet());
            
            // 尝试多种可能的字段名
            Object bizObjectArray = dataMap.get("BizObjectArray");
            if (bizObjectArray == null) {
                bizObjectArray = dataMap.get("Data");
            }
            if (bizObjectArray == null) {
                bizObjectArray = dataMap.get("Items");
            }
            if (bizObjectArray == null) {
                bizObjectArray = dataMap.get("List");
            }
            if (bizObjectArray == null) {
                // 如果没有找到预期的字段，尝试找到第一个List类型的值
                for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
                    if (entry.getValue() instanceof List) {
                        bizObjectArray = entry.getValue();
                        log.debug("找到List类型字段: {}", entry.getKey());
                        break;
                    }
                }
            }
            
            if (bizObjectArray instanceof List) {
                List<Map<String, Object>> dataList = (List<Map<String, Object>>) bizObjectArray;
                log.debug("从Map中解析List，数据条数: {}", dataList.size());
                return dataList;
            } else if (bizObjectArray != null) {
                log.warn("氚云返回数据格式异常，BizObjectArray不是List类型: {}, 类型: {}", 
                        bizObjectArray, bizObjectArray.getClass().getSimpleName());
            } else {
                log.warn("氚云返回Map中未找到数据数组字段，Map内容: {}", dataMap);
            }
        } else {
            log.warn("氚云返回数据格式异常，不是List或Map类型: {}", returnData.getClass());
        }
        
        return new ArrayList<>();
    }
    
    /**
     * 同步结果
     */
    public static class SyncResult {
        private boolean success;
        private String message;
        private String startTime;
        private String endTime;
        private int wechatUserCount;
        private int h3yunExistingCount;
        private int h3yunInsertCount;
        private int h3yunDeleteCount;
        private String errorDetail;
        
        // Getters and Setters
        public boolean isSuccess() {
            return success;
        }
        
        public void setSuccess(boolean success) {
            this.success = success;
        }
        
        public String getMessage() {
            return message;
        }
        
        public void setMessage(String message) {
            this.message = message;
        }
        
        public String getStartTime() {
            return startTime;
        }
        
        public void setStartTime(String startTime) {
            this.startTime = startTime;
        }
        
        public String getEndTime() {
            return endTime;
        }
        
        public void setEndTime(String endTime) {
            this.endTime = endTime;
        }
        
        public int getWechatUserCount() {
            return wechatUserCount;
        }

        public void setWechatUserCount(int wechatUserCount) {
            this.wechatUserCount = wechatUserCount;
        }

        public int getH3yunExistingCount() {
            return h3yunExistingCount;
        }

        public void setH3yunExistingCount(int h3yunExistingCount) {
            this.h3yunExistingCount = h3yunExistingCount;
        }

        public int getH3yunInsertCount() {
            return h3yunInsertCount;
        }

        public void setH3yunInsertCount(int h3yunInsertCount) {
            this.h3yunInsertCount = h3yunInsertCount;
        }

        public int getH3yunDeleteCount() {
            return h3yunDeleteCount;
        }

        public void setH3yunDeleteCount(int h3yunDeleteCount) {
            this.h3yunDeleteCount = h3yunDeleteCount;
        }

        public String getErrorDetail() {
            return errorDetail;
        }

        public void setErrorDetail(String errorDetail) {
            this.errorDetail = errorDetail;
        }
    }
}